import React, { useEffect, useState } from 'react';
import { connect } from 'umi';
import { Form, Button, Row, Col, Divider, Space, Tag, Cascader } from 'antd';
import FormCondition from '@/components/FormCondition';
import DrawerCondition from '@/components/DrawerCondition';
import Uploadjs from '@/utils/aliOssUpload';
import { Segmented } from 'antd';
import { dateDisabled } from '@/common/regular'
import { } from '@/common/contact';
import StageFrom from './components/StageFrom';
import StageConfigurationSetting from '@/components/StageConfigurationSetting';
import moment from 'moment';
const SetForm = (props) => {
  const { dispatch, visible = {}, onClose, handleCallback, loading, hideCard, independentCustomersShow } = props;
  const { show = false, detail = {} } = visible;
  const { id, } = detail;
  const [form] = Form.useForm();
  // 新增修改 传id修改 不传id新增
  const [data, setData] = useState({})
  const [listData, setListData] = useState([])
  const [gjyyData, setGjyyData] = useState([])
  const [stageBaseList, setStageBaseList] = useState([])
  const [modalVisible, setModalVisible] = useState(false)
  const [stageVisible, setStageVisible] = useState(false)
  const [gjData, setGjData] = useState([])
  const [stage, setStages] = useState({
    stageList: [],
    stages: '',
    value: {}
  })
  const { stageList = [], stages, value } = stage
  const [list, setList] = useState([])
  const [gjyyList, setGjyyList] = useState([])
  const [gjList, setGjList] = useState([])
  const [open, setOpen] = useState(false)
  const [formData, setFormData] = useState({
    potential: {},
    cultivate: {},
    sells: {},
    service: {}
  })
  const [hesitateStage, setHesitateStage] = useState('')
  const [followStage, setFollowStage] = useState('')
  const [questionStage, setQuestionStage] = useState('')
  const filterBaseList = stageBaseList.reduce((item, val) => {
    const {
      subStageInfoList = [],
      stageInfo = {}
    } = val
    const { stageIdentification } = stageInfo
    return [
      ...item,
      {
        ...val,
        stageInfo: {
          ...stageInfo,
          baseStageFlag: '1',
          mainStage: '',
        }
      },
      ...subStageInfoList.map(c => {
        return {
          stageInfo: {
            ...c,
            mainStage: stageIdentification
          }
        }
      }),
    ]
  }, [])
  const initStageList = () => {
    const initStage = filterBaseList.reduce((item, val) => {
      if (val.stageInfo.stageIdentification === stages) {
        return val
      }
      return item
    }, {})

    const { stageInfo = {}
    } = initStage
    let index = null
    const { mainStage, stageIdentification, baseStageFlag } = stageInfo
    if (baseStageFlag === '1') {
      index = stageBaseList.findIndex(val => val.stageInfo.stageIdentification === stageIdentification)
    }
    else {
      index = stageBaseList.findIndex(val => val.stageInfo.stageIdentification === mainStage)
    }
    return stageBaseList.filter((val, c) => {
      return c <= index
    }).map((val, c) => {
      const { stageInfo = {},
        subStageInfoList = []
      } = val
      if (c === index) {
        if (baseStageFlag !== '1') {
          return {
            ...stageInfo,
            subStageInfoList: [{ ...initStage.stageInfo }]
          }
        }
        return {
          ...stageInfo,
          subStageInfoList
        }
      }
      return {
        ...stageInfo,
        subStageInfoList
      }
    })
  }
  const findFatherData = (stages) => {
    const initStage = filterBaseList.reduce((item, val) => {
      if (val.stageInfo.stageIdentification === stages) {
        return val
      }
      return item
    }, {})
    const { stageInfo = {}
    } = initStage
    const { mainStage, stageIdentification, baseStageFlag } = stageInfo
    if (baseStageFlag === '1') {
      return [stageIdentification]
    }

    else {
      return [mainStage, stageIdentification]
    }
  }
  const fetchGjyy = () => {
    if (gjyyData.length > 0) {
      return
    }
    dispatch({
      type: 'user/fetchFollowUpQuestionType',
      callback: (e) => {
        const { stageItemList = [] } = e
        setGjyyData(stageItemList)
      },
    });
  };
  const fetchGj = () => {
    if (gjData.length > 0) {
      return
    }
    dispatch({
      type: 'user/fetchFollowUpStatus',
      payload: {
        organizationUserId: id,
        searchFor: 'user'
      },
      callback: (e) => {
        const { stageItemList = [] } = e
        setGjData(stageItemList)
      },
    });
  };
  const fetchList = () => {
    if (list.length > 0) {
      return
    }
    dispatch({
      type: 'user/fetchListHesitate',
      callback: (e) => {
        const { stageItemList = [] } = e
        setListData(stageItemList)
      },
    });
  };
  const fetchDetail = () => {
    dispatch({
      type: 'subscriber/fetchUserDetailSimpleInfo',
      payload: {
        organizationUserId: id,
      },
      callback: (e) => {
        const { expectedRegistrationDate } = e
        setData({ expectedRegistrationDate: expectedRegistrationDate ? moment(expectedRegistrationDate, 'YYYY-MM-DD') : '' })
      },
    });
  }
  const fetchCanPreApplyStage = () => {
    // dispatch({
    //   type: 'subscriber/fetchtCanPreApplyStage',
    //   payload: {
    //     organizationUserId: id
    //   },
    //   callback: (e) => {
    //     let data = {
    //       stageList: e.map(item => {
    //         const { stage } = item
    //         return {
    //           ...item,
    //           label: stage_tab[stage],
    //           value: stage
    //         }
    //       }),
    //       stages: e[0].stage,
    //       value: e[0]
    //     }

    //     setStages(data)
    //   }
    // })
  }
  const fetchBase = () => {
    dispatch({
      type: 'user/fetchUserStageForChoose',
      payload: {
        queryFor: 'followUp',
        organizationUserId: id
      },
      callback: (e = []) => {
        const { stageInfoList = [] } = e
        setStageBaseList(stageInfoList)
      }
    })
  }
  const setFetchGj = () => {
    const followBaseList = gjData.reduce((item, val) => {
      const {
        subStageItemList = [],
        stageInfo = {}
      } = val
      const { stageIdentification } = stageInfo
      return [
        ...item,
        {
          ...val,
          stageInfo: {
            ...stageInfo,
            baseStageFlag: '1',
          }
        },
        ...subStageItemList.map(c => {
          return {
            ...c,
            stageInfo: {
              ...c.stageInfo,
              mainStage: stageIdentification
            }
          }
        }),
      ]
    }, [])
    setGjList(followBaseList.reduce((item, val) => {
      if (val.stageInfo.stageIdentification === followStage) {
        return val.followUpStatusList
      }
      return item
    }, []))
  }
  const setGjyy = () => {
    const questionBaseList = gjyyData.reduce((item, val) => {
      const {
        subStageItemList = [],
        stageInfo = {}
      } = val
      const { stageIdentification } = stageInfo
      return [
        ...item,
        {
          ...val,
          stageInfo: {
            ...stageInfo,
            baseStageFlag: '1',
          }
        },
        ...subStageItemList.map(c => {
          return {
            ...c,
            stageInfo: {
              ...c.stageInfo,
              mainStage: stageIdentification
            }
          }
        }),
      ]
    }, [])
    setGjyyList(questionBaseList.reduce((item, val) => {
      if (val.stageInfo.stageIdentification === questionStage) {
        return val.followUpQuestionTypeList
      }

      return item
    }, []))
  }
  const setFetchList = () => {
    const hesitateBaseList = listData.reduce((item, val) => {
      const {
        subStageItemList = [],
        stageInfo = {}
      } = val
      const { stageIdentification } = stageInfo
      return [
        ...item,
        {
          ...val,
          stageInfo: {
            ...stageInfo,
            baseStageFlag: '1',
          }
        },
        ...subStageItemList.map(c => {
          return {
            ...c,
            stageInfo: {
              ...c.stageInfo,
              mainStage: stageIdentification
            }
          }
        }),
      ]
    }, [])
    setList(hesitateBaseList.reduce((item, val) => {
      if (val.stageInfo.stageIdentification === hesitateStage) {
        return val.hesitateList
      }

      return item
    }, []))
  }
  const fetchRoleEdit = () => {
    form.validateFields().then(async (values) => {
      const { id } = detail;
      const { images, nextFollowUpTime, attachment, content, hesitateId = [], followUpStatusId = [], followUpQuestionTypeId = [], expectedRegistrationDate } = values;
      const img = (await Uploadjs(images)) || [];
      // const file = (await Uploadjs(attachment)) || [];
      dispatch({
        type: 'subscriber/fakeInsertFollowUp',
        payload: {
          stage: stages,
          content,
          organizationUserId: id,
          images: img.toString(),
          // attachment: file.toString(),
          hesitateId: hesitateId.toString(),
          followUpStatusId: followUpStatusId.toString(),
          followUpQuestionTypeId: followUpQuestionTypeId.toString(),
          nextFollowUpTime:
            nextFollowUpTime ? moment(nextFollowUpTime).format('YYYY-MM-DD') : '',
          expectedRegistrationDate: expectedRegistrationDate ? moment(expectedRegistrationDate).format('YYYY-MM-DD') : '',
        },
        callback: () => {
          onClose();
          handleCallback && handleCallback()
        },
      });
    });
  };
  console.log(filterBaseList, stage, 'follow')
  useEffect(() => {
    if (show) {
      fetchBase()
      fetchGjyy()
      fetchList()
      fetchGj()
    } else {
      setOpen(false)
      setFormData({})
      setHesitateStage('')
      setFollowStage('')
      setQuestionStage('')
      setStageBaseList([])
    }
  }, [show])
  useEffect(() => {
    if (show) {
      fetchDetail()
      fetchCanPreApplyStage()
    } else {
      setData({})
      setStages({
        list: [],
        stages: '',
        value: {}
      })
    }
  }, [show])
  useEffect(() => {
    setHesitateStage(stages)
    setFollowStage(stages)
    setQuestionStage(stages)
  }, [stage])
  useEffect(() => {
    setFetchList()
  }, [hesitateStage, listData])
  useEffect(() => {
    setFetchGj()
  }, [followStage, gjData])
  useEffect(() => {
    setGjyy();
  }, [questionStage, gjyyData])

  console.log(hesitateStage, initStageList(hesitateStage), '11111')

  const { hesitateId = [], followUpStatusId = '', followUpQuestionTypeId = [] } = formData[stages] || {}
  const renderfilter = (id) => {
    if (id === followUpStatusId) {
      return true
    }
    else {
      return false
    }

  }
  const formItems = [
    {
      label: '跟进内容',
      name: 'content',
      type: 'textArea',
    },
    {
      label: '图片',
      name: 'images',
      type: 'upload',
      rules: [{ required: (hesitateId.length || followUpStatusId || followUpQuestionTypeId.length) ? true : false }],
    },
    {
      label: '犹豫原因',
      name: 'hesitateId',
      type: 'select',
      onChange: (e) => {
        setFormData((s) => {
          return {
            ...s,
            [stages]: {
              ...formData[stages],
              hesitateId: e
            }
          }
        })
      },
      mode: "multiple",
      dropdownRender: (menu) => {
        return <div style={{ minHeight: 300 }}>
          <div id='select_cascader' onClick={(e) => e.stopPropagation()}>
            <Cascader
              getPopupContainer={() => document.getElementById('select_cascader')}
              expandTrigger={'hover'}
              fieldNames={{ label: 'stageName', value: 'stageIdentification', children: 'subStageInfoList' }}
              style={{ marginLeft: 12, width: '50%' }}
              value={findFatherData(hesitateStage)}
              onChange={async (e) => {
                if (e && e.length) {
                  setHesitateStage(e[e.length - 1])
                }
              }}
              options={initStageList(hesitateStage)}></Cascader>
          </div>

          <Divider
            style={{
              margin: '8px 0',
            }}
          />
          {menu}
        </div>
      },
      fieldNames: { label: 'hesitateReason', value: 'id' },
      select: list,
      rules: [{ required: false }],
    },
    {
      label: '跟进状态',
      name: 'followUpStatusId',
      type: 'select',
      select: gjList,
      // mode: "multiple",
      onChange: (e) => {
        // setFormData((s) => {
        //   return {
        //     ...s,
        //     [stages]: {
        //       ...formData[stages],
        //       followUpStatusId: e
        //     }
        //   }
        // })
      },
      dropdownRender: (menu) => {
        return <div style={{ minHeight: 300 }} onClick={(e) => {
          e.stopPropagation()
        }}>
          <div id='select_cascader' onClick={(e) => e.stopPropagation()}>
            <Cascader
              getPopupContainer={() => document.getElementById('select_cascader')}
              expandTrigger={'hover'}
              fieldNames={{ label: 'stageName', value: 'stageIdentification', children: 'subStageInfoList' }}
              style={{ marginLeft: 12, width: '50%' }}
              value={findFatherData(followStage)}
              onChange={async (e) => {
                if (e && e.length) {
                  setFollowStage(e[e.length - 1])
                }
              }}
              options={initStageList()}></Cascader>
          </div>
          <Divider
            style={{
              margin: '8px 0',
            }}
          />
          <Row style={{ overflowY: 'auto' }} gutter={[12, 12]}>
            <Col span={24}>
              <div style={{ padding: 12 }} >
                <div>未跟进</div>
                <div style={{ marginTop: 8 }}>
                  <Space>
                    {gjList && gjList.map((item, index) => {
                      if (!item.userDoneFlag) {
                        return <Tag
                          style={{ cursor: 'pointer' }}
                          color={item.id === followUpStatusId ? 'geekblue' : 'default'}
                          onClick={(e) => {
                            setFormData((s) => {
                              return {
                                ...s,
                                [stages]: {
                                  ...formData[stages],
                                  followUpStatusId: item.id
                                }
                              }
                            })
                            form.setFieldsValue({
                              'followUpStatusId': item.id
                            })
                          }} key={index}>{item.followUpStatus}</Tag>
                      }
                    })}
                  </Space>
                </div>
              </div>
            </Col>
            <Col span={24}>
              <div style={{ padding: 12 }} >
                <div>已跟进</div>
                <div style={{ marginTop: 8 }}>
                  <Space>
                    {gjList && gjList.map((item, index) => {
                      if (item.userDoneFlag) {
                        return <Tag style={{ cursor: 'pointer' }}
                          color={item.id === followUpStatusId ? 'geekblue' : 'default'}
                          onClick={(e) => {
                            setFormData((s) => {
                              return {
                                ...s,
                                [stages]: {
                                  ...formData[stages],
                                  followUpStatusId: item.id
                                }
                              }
                            })
                            form.setFieldsValue({
                              'followUpStatusId': item.id
                            })
                          }} key={index}>{item.followUpStatus}</Tag>
                      }
                    })}
                  </Space>
                </div>
              </div>

            </Col>
          </Row >
        </div>
      },
      rules: [{ required: false }],
      fieldNames: { label: 'followUpStatus', value: 'id' },
    },
    {
      label: '跟进问题',
      name: 'followUpQuestionTypeId',
      type: 'select',
      rules: [{ required: false }],
      select: gjyyList,
      mode: "multiple",
      onChange: (e) => {
        setFormData((s) => {
          return {
            ...s,
            [stages]: {
              ...formData[stages],
              followUpQuestionTypeId: e
            }
          }
        })
      },
      dropdownRender: (menu) => {
        return <>
          <div style={{ minHeight: 300 }} id='select_cascader' onClick={(e) => e.stopPropagation()}>
            <Cascader
              getPopupContainer={() => document.getElementById('select_cascader')}
              expandTrigger={'hover'}
              fieldNames={{ label: 'stageName', value: 'stageIdentification', children: 'subStageInfoList' }}
              style={{ marginLeft: 12, width: '50%' }}
              value={findFatherData(questionStage)}
              onChange={async (e) => {
                if (e && e.length) {
                  setQuestionStage(e[e.length - 1])
                }
              }}
              options={initStageList(questionStage)}></Cascader>
            <Divider
              style={{
                margin: '8px 0',
              }}
            />
            {menu}
          </div>

        </>
      },
      fieldNames: { label: 'questionType', value: 'id' },
    },
    {
      label: '下次跟进时间',
      name: 'nextFollowUpTime',
      type: 'dataPicker',
      disabledDate: dateDisabled,
      rules: [{ required: false }],
      format: 'YYYY-MM-DD',
    },
    {
      label: '预计报名时间',
      name: 'expectedRegistrationDate',
      type: 'dataPicker',
      rules: [{ required: false }],
      format: 'YYYY-MM-DD',
    },
    // {
    //   label: '附件',
    //   name: 'attachment',
    //   type: 'otherUpload',
    //   maxFile: 10,
    //   rules: [{ required: false }],
    // },
  ];
  const setMessage = () => {
    const initStage = filterBaseList.reduce((item, val) => {
      if (val.stageInfo.stageIdentification === stages) {
        return val
      }
      return item
    }, {})
    const { stageInfo = {} } = initStage
    const { canApplyFlag, adminAuthFlag, applyDoingFlag, canFollowUpFlag, publicFlag } = stageInfo
    if (publicFlag === '1') {
      return '当前阶段在公海，请前往公海认领'
    }
    else if (adminAuthFlag == '0' && applyDoingFlag == '1') {
      return '权限已申请，请耐心等待审核'
    }
    else if (adminAuthFlag == '0' && applyDoingFlag == '0' && (canApplyFlag == '1' && canFollowUpFlag == '1')) {
      if (stages === 'service') {
        return '服务阶段暂时不支持申请'
      }
      return '点击申请获取跟进权限'
    } else if (adminAuthFlag == '0' && canApplyFlag == '0' && canFollowUpFlag == '0') {
      return '当前阶段已完成，无权限跟进，且无法申请。'
    }
  }
  const setButton = () => {
    const initStage = filterBaseList.reduce((item, val) => {
      if (val.stageInfo.stageIdentification === stages) {
        return val
      }
      return item
    }, {})
    const { stageInfo = {} } = initStage
    const { canApplyFlag, adminAuthFlag, applyDoingFlag, canFollowUpFlag, publicFlag } = stageInfo
    if (publicFlag === '1') {
      return <Button type="primary" loading={loading} onClick={() => {
        dispatch({
          type: 'subscriber/fakeClaimPublicUser', payload: {
            userIdList: [id],
            stage: stages,
            claimFrom: independentCustomersShow ? 'noShareTypeProtect' : ''
          }, callback: (e) => {
            onClose()
            handleCallback()
          }
        })
      }}>
        认领
      </Button>
    }
    else if (adminAuthFlag == '0' && applyDoingFlag == '0' && canApplyFlag == '1' && canFollowUpFlag == '1') {
      return <Button type="primary" loading={loading} onClick={() => {
        setStageVisible({
          show: true,
          detail: {
            id: id, stage: stages
          }
        })
      }}>
        申请
      </Button>
    }

    else if (adminAuthFlag === '1') {
      return <Button type="primary" loading={loading} onClick={fetchRoleEdit}>
        确定
      </Button>
    }
    else {
      return null
    }
  }
  const modalProps = {
    title: `跟进`,
    visible: show,
    onClose,
    maskClosable: true,
    destroyOnClose: true,
    footer: (setButton()),
  };
  return (
    <div onClick={() => {
      setOpen(false)
    }}>
      <DrawerCondition {...modalProps}>
        <Col span={24}>
          <StageConfigurationSetting NoCard={true} onChange={async (e, { mainStage }) => {
            const inval = await form.getFieldsValue() || {}
            form.resetFields()
            if (formData[e]) {
              form.setFieldsValue({
                ...data,
                ...formData[e]
              })
            }
            setStages(() => {
              setFormData((s) => {
                return {
                  ...s,
                  [stages]: inval
                }
              })
              return {
                ...stage,
                stages: e,
                // value: stageList.filter(item => {
                //   return item.stage === e || mainStage === item.stage
                // })[0]
              }
            })
          }} data={filterBaseList}></StageConfigurationSetting>
        </Col>
        <FormCondition form={form} formItems={formItems} initialValues={data}></FormCondition>
        <Row gutter={[24, 24]}>
          <Col style={{ marginBottom: 24 }} offset={3}>
            <div style={{ color: 'red' }}>
              {setMessage()}
            </div>
          </Col>
        </Row>
        <StageFrom
          onClose={() => { setStageVisible(false) }}
          visible={stageVisible}
          handleCallback={() => {
            setStageVisible(false)
            onClose();
          }}></StageFrom>
      </DrawerCondition>
    </div>

  );
};

export default connect(({ loading }) => ({
  loading: loading.effects['subscriber/fakeInsertFollowUp'],
}))(SetForm);
